package com.leyou.user.web;

import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.service.UserService;
import com.netflix.discovery.converters.Auto;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 校验用户名和手机号
     * @param data  用户名或者手机号
     * @param type  1：就是用户名；   2：就是手机号码
     * @return      true：可用      false：不可用
     */
    @GetMapping("/check/{data}/{type}")
    @ApiOperation(value = "校验用户名数据是否可用，如果不存在则可用")
    @ApiResponses({
            @ApiResponse(code = 200, message = "校验结果有效，true或false代表可用或不可用"),
            @ApiResponse(code = 400, message = "请求参数有误，比如type不是指定值")
    })
    public ResponseEntity<Boolean> check(@ApiParam(value = "要校验的数据", example = "lisi") @PathVariable("data") String data,
                                         @ApiParam(value = "数据类型，1：用户名，2：手机号", example = "1") @PathVariable("type") Integer type){
        return ResponseEntity.ok(userService.check(data, type));
    }

    /**
     * 发送短信验证码
     * @param phone     用户手机号码
     * @return          没有返回值
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone") String phone){
        userService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 用户注册
     * @param user      用于接收参数的DTO
     * @param code      用户传入的验证码
     * @return          无返回值
     */
    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid /*校验对象中的属性*/ UserDTO user, BindingResult result, @RequestParam("code") String code){
        // 校验用户数据
        if(result.hasErrors()){
            List<ObjectError> allErrors = result.getAllErrors();
            String msg = allErrors.stream()
                    .map(ObjectError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new LyException(400, msg);
        }
        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据用户名称和密码查询用户
     * @param username  用户名
     * @param password  密码
     * @return
     */
    @GetMapping("/query")
    public ResponseEntity<UserDTO> queryUserByUsernameAndPassword(@RequestParam("username") String username,
                                                                  @RequestParam("password") String password, HttpServletRequest request){
        UserDTO userDTO = userService.queryUserByUsernameAndPassword(username, password);
        return ResponseEntity.ok(userDTO);
    }
}
